import 'dart:math';

import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_first_station/muyu/history_page.dart';
import 'package:flutter_first_station/muyu/models/audio_option.dart';
import 'package:flutter_first_station/muyu/options/select_audio.dart';
import 'package:flutter_first_station/muyu/options/select_image.dart';
import 'package:flutter_first_station/storage/db_storage.dart';
import 'package:flutter_first_station/storage/sp_storage.dart';
import 'package:uuid/uuid.dart';

import 'models/image_option.dart';
import 'models/merit_record.dart';

class MuYuPage extends StatefulWidget {
  const MuYuPage({super.key});

  @override
  State<MuYuPage> createState() => _MuYuPageState();
}

class _MuYuPageState extends State<MuYuPage>
    with AutomaticKeepAliveClientMixin {
  final Random _random = Random();
  final Uuid uuid = const Uuid();
  int _counter = 0;
  int _curValue = 0;
  MeritRecord? _curRecord;
  AudioPool? pool;
  late List<MeritRecord> _records = []; // 记录点击

  final List<ImageOption> imageOptions = const [
    ImageOption('基础版', 'assets/images/muyu01.png', 1, 3),
    ImageOption('尊享版', 'assets/images/muyu02.png', 3, 6),
  ];

  final List<AudioOption> audioOptions = const [
    AudioOption('音效1', 'muyu_1.mp3'),
    AudioOption('音效2', 'muyu_2.mp3'),
    AudioOption('音效3', 'muyu_3.mp3'),
  ];

  int _activeImageIndex = 0;
  int _activeAudioIndex = 0;

  // 激活图像
  String get activeImage => imageOptions[_activeImageIndex].src;

  // 激活声音
  String get activeAudio => audioOptions[_activeAudioIndex].src;

  // 激活点击功德值
  int get knockValue {
    int min = imageOptions[_activeImageIndex].min;
    int max = imageOptions[_activeImageIndex].max;
    return min + _random.nextInt(max + 1 - min);
  }

  /// 跳转到历史
  void _toHistory() {
    Navigator.of(context).push(MaterialPageRoute(
        builder: (_) => RecordHistory(records: _records.reversed.toList())));
  }

  /// 点击选择敲打声音
  void _onTapSelectAudio() {
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return AudioOptionPanel(
              audioOptions: audioOptions,
              activeIndex: _activeAudioIndex,
              onSelect: _onSelectAudio);
        });
  }

  /// 点击选择木鱼图片
  void _onTapSelectImage() {
    // 弹窗
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return ImageOptionPanel(
              imageOptions: imageOptions,
              activeIndex: _activeImageIndex,
              onSelect: _onSelectImage);
        });
  }

  void _onSelectImage(int value) {
    Navigator.of(context).pop(); // 关闭弹窗
    if (value == _activeImageIndex) return;
    setState(() {
      _activeImageIndex = value;
      saveConfig();
    });
  }

  void _onSelectAudio(int value) async {
    Navigator.of(context).pop(); // 关闭弹窗
    if (value == _activeAudioIndex) return;
    _activeAudioIndex = value;
    saveConfig();
    pool = await FlameAudio.createPool(activeAudio, maxPlayers: 1);
  }

  /// 点击木鱼
  void _onTap() {
    pool?.start();
    setState(() {
      //_curValue = 1 + _random.nextInt(3);
      _curValue = knockValue;
      _counter += _curValue;

      // 添加功德记录
      String id = uuid.v4();
      _curRecord = MeritRecord(id, DateTime.now().millisecondsSinceEpoch,
          _curValue, activeImage, audioOptions[_activeAudioIndex].name);
      saveConfig();
      DBStorage.instance.meritRecordDao.insert(_curRecord!);
      _records.add(_curRecord!);
    });
  }

  /// 初始化播放音效
  void _initAudioPool() async {
    pool = await FlameAudio.createPool('muyu_1.mp3', maxPlayers: 4);
  }

  void saveConfig() {
    SpStorage.instance.saveMuYu(
        counter: _counter,
        activeImageIndex: _activeImageIndex,
        activeAudioIndex: _activeAudioIndex);
  }

  /// 读取木鱼缓存
  void _initConfig() async {
    Map<String, dynamic> config = await SpStorage.instance.readMuYuConfig();
    _counter = config["counter"] ?? 0;
    _activeImageIndex = config["activeImageIndex"] ?? 0;
    _activeAudioIndex = config["activeAudioIndex"] ?? 0;
    _records = await DBStorage.instance.meritRecordDao.query();
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _initAudioPool();
    _initConfig();
  }

  @override
  void dispose() {
    pool?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("电子木鱼"),
        actions: [
          IconButton(onPressed: _toHistory, icon: const Icon(Icons.history))
        ],
      ),
      body: Column(
        children: [
          // 上半部分
          Expanded(
            child: CountPanel(
                count: _counter,
                onSelectAudio: _onTapSelectAudio,
                onSelectImage: _onTapSelectImage),
          ),
          // 下半部分
          Expanded(
            child: Stack(
              alignment: Alignment.topCenter,
              children: [
                MuYuAssetsImage(image: activeImage, onTap: _onTap),
                if (_curValue != 0) AnimateText(record: _curRecord!),
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

/// 上半部分内容
class CountPanel extends StatelessWidget {
  final int count;
  final VoidCallback onSelectAudio;
  final VoidCallback onSelectImage;

  const CountPanel(
      {super.key,
      required this.count,
      required this.onSelectAudio,
      required this.onSelectImage});

  @override
  Widget build(BuildContext context) {
    // 按钮样式
    final ButtonStyle style = ElevatedButton.styleFrom(
      minimumSize: const Size(36, 36), // 最小尺寸
      padding: EdgeInsets.zero, // 边距
      backgroundColor: Colors.greenAccent,
      elevation: 0, // 阴影深度
    );

    return Stack(
      children: [
        Center(
          child: Text(
            '功德数：$count',
            style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
        ),
        Positioned(
            right: 10,
            top: 10,
            // 使用竖直方向的 Wrap
            child: Wrap(
              spacing: 8,
              direction: Axis.vertical,
              children: [
                ElevatedButton(
                    style: style,
                    onPressed: onSelectAudio,
                    child: const Icon(Icons.music_note_outlined)),
                ElevatedButton(
                    style: style,
                    onPressed: onSelectImage,
                    child: const Icon(Icons.image))
              ],
            ))
      ],
    );
  }
}

/// 下半部分内容
class MuYuAssetsImage extends StatelessWidget {
  final String image;
  final VoidCallback onTap;

  const MuYuAssetsImage({super.key, required this.image, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return Center(
      // 使用 GestureDetector 监听手势回调
      child: GestureDetector(
        onTap: onTap,
        child: Image.asset(
          image,
          height: 200,
        ),
      ),
    );
  }
}

/// 动画文字效果
class AnimateText extends StatefulWidget {
  //final String text;
  final MeritRecord record;

  const AnimateText({super.key, required this.record});

  @override
  State<AnimateText> createState() => _FadTextState();
}

class _FadTextState extends State<AnimateText>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> opacity;
  late Animation<Offset> position;
  late Animation<double> scale;

  @override
  void initState() {
    super.initState();
    // 初始化动画相关
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 500));
    // 透明度变化
    opacity = Tween(begin: 1.0, end: 0.0).animate(controller);
    // 缩放变换 从 1 ~ 0.9 变化
    scale = Tween(begin: 1.0, end: 0.9).animate(controller);
    // 在竖直方向上的偏移量，从两倍子组件高度变化到 0
    position = Tween<Offset>(begin: const Offset(0, 2), end: Offset.zero)
        .animate(controller);
    controller.forward();
  }

  @override
  void didUpdateWidget(covariant AnimateText oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 根据记录的id判断是否需要弹动画效果
    if (oldWidget.record.id != widget.record.id) {
      controller.forward(from: 0);
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /// 移动、缩放、透明度动画
    return ScaleTransition(
      scale: scale,
      child: SlideTransition(
        position: position,
        child: FadeTransition(
          opacity: opacity,
          child: Text('功德+${widget.record.value}'),
        ),
      ),
    );
  }
}
